/**
 * 音频提取器类
 * 负责从音视频元素中提取音频流，为语音识别提供输入
 */
class AudioExtractor {
  /**
   * 初始化音频提取器
   */
  constructor() {
    this.audioContext = null
    this.isProcessing = false
    this.currentStream = null
    this.analyser = null
    this.source = null
    this.destination = null
    console.log('AudioExtractor初始化完成')
  }

  /**
   * 初始化Web Audio API
   */
  async initAudioContext() {
    try {
      if (!this.audioContext) {
        this.audioContext = new (window.AudioContext || window.webkitAudioContext)()
        console.log('Web Audio Context初始化成功')
      }
      return this.audioContext
    } catch (error) {
      console.error('初始化AudioContext失败:', error)
      throw error
    }
  }

  /**
   * 从媒体元素中提取音频流
   * @param {MediaElement} element - 媒体元素（audio或video）
   * @returns {Promise<MediaStream>} 音频流
   */
  async extractAudioStream(element) {
    console.log('开始提取音频流:', element)

    if (!element) {
      throw new Error('媒体元素不能为空')
    }

    try {
      // 初始化AudioContext
      await this.initAudioContext()

      // 检查元素是否正在播放
      if (element.paused) {
        console.log('媒体元素未播放，尝试播放')
        await this.playMediaElement(element)
      }

      // 创建MediaStreamSource
      this.source = this.audioContext.createMediaElementSource(element)

      // 创建Analyser节点用于音频分析
      this.analyser = this.audioContext.createAnalyser()
      this.analyser.fftSize = 2048

      // 创建MediaStreamDestination来获取音频流
      this.destination = this.audioContext.createMediaStreamDestination()

      // 连接音频节点
      this.source.connect(this.analyser)
      this.analyser.connect(this.destination)
      this.analyser.connect(this.audioContext.destination) // 保持音频输出

      // 获取音频流
      const audioStream = this.destination.stream

      // 保存当前流引用
      this.currentStream = audioStream
      this.isProcessing = true

      console.log('音频流提取成功，流轨道数:', audioStream.getAudioTracks().length)
      return audioStream
    } catch (error) {
      console.error('提取音频流失败:', error)
      throw error
    }
  }

  /**
   * 播放媒体元素
   * @param {MediaElement} element - 媒体元素
   */
  async playMediaElement(element) {
    try {
      // 尝试播放
      const playPromise = element.play()
      if (playPromise !== undefined) {
        await playPromise
        console.log('媒体元素播放成功')
      }
    } catch (error) {
      console.warn('自动播放失败，需要用户交互:', error)
      // 这里可以触发用户交互提示
      throw new Error('需要用户交互才能播放媒体')
    }
  }

  /**
   * 获取音频分析数据
   * @returns {Object} 音频分析数据
   */
  getAudioAnalytics() {
    if (!this.analyser) {
      return null
    }
    const bufferLength = this.analyser.frequencyBinCount
    const dataArray = new Uint8Array(bufferLength)
    this.analyser.getByteFrequencyData(dataArray)
    // 计算音频强度
    const average = dataArray.reduce((sum, value) => sum + value, 0) / bufferLength
    return {
      frequencyData: dataArray,
      averageIntensity: average,
      timestamp: Date.now(),
    }
  }

  /**
   * 停止音频提取
   */
  stopExtraction() {
    console.log('停止音频提取')
    if (this.source) {
      this.source.disconnect()
      this.source = null
    }
    if (this.analyser) {
      this.analyser.disconnect()
      this.analyser = null
    }
    if (this.destination) {
      this.destination.disconnect()
      this.destination = null
    }
    this.isProcessing = false
    this.currentStream = null
  }

  /**
   * 清理资源
   */
  cleanup() {
    console.log('清理AudioExtractor资源')
    this.stopExtraction()
    if (this.audioContext) {
      this.audioContext.close()
      this.audioContext = null
    }
  }
}

export default AudioExtractor
